package com.xzj.admin.analysis.base.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xzj.admin.analysis.base.constants.CommonEnums;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.util.Arrays;
import java.util.List;
import java.util.TreeMap;

/**
 * @program: xzj-admin
 * @ClassName: AnalysisCommonUtil
 * @description: 解析公共方法
 * @author: XiaZunJun
 * @create: 2024-11-11 16:34
 */
@Slf4j
public class AnalysisCommonUtil {
    /**
     * 功能根据入参拼接相应字符串
     *
     * @param params 需用通用组装的字段集合
     * @return String
     * @author xiazunjun
     * @date 2023/8/16 15:09
     */
    public static String commonBuildStr(String... params) {
        return buildByJoinChar(CommonEnums.JOIN.DEFAULT.getValue(), params);
    }

    public static String buildByJoinChar(String joinChar, String... params) {
        StringBuilder strBuilder = new StringBuilder();
        for (String param : params) {
            strBuilder.append(param).append(joinChar);
        }
        String redisKey = strBuilder.toString();
        return redisKey.substring(0, redisKey.length() - 1);
    }

    /**
     * 统一组装redis key的组转方法，保证前置一致
     *
     * @param theme 消息源主题
     * @return String
     * @author xiazunjun
     * @date 2023/10/8 11:08
     */
    public static String unifyBuildRedisKey(String cloudId,String cloudType,String rmPoolId,String standardCode,String theme) {
        String cloudKey = CommonEnums.CLOUD_ID.convertCloudId(cloudId);
        String firstKey =
                commonBuildStr(cloudKey, cloudId, cloudType, standardCode, rmPoolId);
        if (CommonEnums.CLOUD_TYPE.DEFAULT.equals(cloudType)) {
            firstKey = commonBuildStr(cloudKey, cloudId, standardCode, rmPoolId);
        }
        if (StrUtil.isNotEmpty(theme)) {
            firstKey = commonBuildStr(firstKey, theme);
        }
        return firstKey;
    }

    /**
     * 源表字段涉及多层次字段获取时的数据处理方法
     *
     * @param row       具体需要转化的资源实体对象
     * @param fieldName 具体需要模转的资源字段名
     * @author xiazunjun
     * @date 2023/12/18 9:32
     */
    public static Object multiLevelFieldConvert(JSONObject row, String fieldName) {
        Object result = null;
        if (fieldName.contains(".")) {
            String[] fileNames = fieldName.split("\\.");
            JSONObject jsonObject = row;
            for (int i = 0; i < fileNames.length; i++) {
                if (null == jsonObject) {
                    //log.debug("获取jsonObject对象为空，导致无法执行,{}", fieldName);
                    break;
                }
                if (i < (fileNames.length - 1)) {
                    Object fieldObj = jsonObject.get(fileNames[i]);
                    if (fieldObj instanceof JSONArray) {
                        jsonObject = jsonObject.getJSONArray(fileNames[i]).getJSONObject(0);
                    } else {
                        jsonObject = jsonObject.getJSONObject(fileNames[i]);
                    }
                } else {
                    result = jsonObject.get(fileNames[i]);
                }
            }
        } else {
            result = row.get(fieldName);
        }
        return result;
    }

    /**
     * 字符串进行MD5值计算
     *
     * @return
     * @author xiazunjun
     * @date 2023/4/26 8:34
     */
    public static String objectToMd5(String jsonObject, String... excludeKeys) {
        String convertJson = jsonObject;
        TreeMap paramTreeMap = JSON.parseObject(convertJson, TreeMap.class);
        if (excludeKeys != null) {
            List<String> dedupExcludeKeys = Arrays.asList(excludeKeys);
            if (!dedupExcludeKeys.isEmpty()) {
                for (String dedupExcludeKey : dedupExcludeKeys) {
                    paramTreeMap.remove(dedupExcludeKey);
                }
            }
        }
        String paramTreeMapJSON = JSON.toJSONString(paramTreeMap);
        String md5deDupParam = jdkMD5(paramTreeMapJSON);
        log.debug("md5deDupParam = {}, excludeKeys = {} {}", md5deDupParam, Arrays.deepToString(excludeKeys),
                paramTreeMapJSON);
        return md5deDupParam;
    }

    private static String jdkMD5(String src) {
        String res = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] mdBytes = messageDigest.digest(src.getBytes());
            res = printHexBinary(mdBytes);
        } catch (Exception e) {
            log.error("", e);
        }
        return res;
    }

    private static String printHexBinary(byte[] hash) {
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }
}
